package com.lzs.Controller;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lzs.PO.Certificate;
import com.lzs.PO.Member;
import com.lzs.PO.Page;
import com.lzs.PO.Partdetail;
import com.lzs.PO.Policy;
import com.lzs.PO.Reimbursement;
import com.lzs.Service.CertificateService;
import com.lzs.Service.MemberService;
import com.lzs.Service.PartdetailService;
import com.lzs.Service.PolicyService;
import com.lzs.Service.ReimbursementService;
import com.lzs.util.Msg;

@Controller
@RequestMapping(value = "/reimbursement")
public class ReimbursementController {
	@Autowired
	private MemberService memberService;
	@Autowired
	private PartdetailService partdetailService;
	@Autowired
	private CertificateService certificateService;
	@Autowired
	private PolicyService policyService;
	@Autowired
	private ReimbursementService reimbursementService;
	
	@RequestMapping(value = "/people_check_open")
	public String openPeopleCheck() {
		
		return"/reimbursement/people_check";
	}

	@RequestMapping(value = "/people_check")
	public String checkPeople(String people_id,Model model) {
		// 1.通过people_id查出对应的rural_id
		Member member = this.memberService.findMemberByPeopleId(people_id);
		// 2.通过rural_id查询参合详情表，限定条件为当年年份
		SimpleDateFormat currentYear = new SimpleDateFormat("yyyy");
		String year = currentYear.format(new java.util.Date());
		System.out.println(people_id);
		System.out.println(member);
		Partdetail partdetail = this.partdetailService.findPartdetailByRuralIdAndYear(member.getRural_id(),year);
		// 3.判断查询记录，不为null则跳转至报销表界面，为null则重写跳转至身份证核对界面
		
		if(null!=partdetail) {
			
			model.addAttribute("member", member);
			
			return"/reimbursement/reimbursement_check";
		}else {
			
			model.addAttribute("msg", "该身份证号未参合！");
			
			model.addAttribute("member", member);
			
			return"/reimbursement/people_check";
		}
	}
	
	@RequestMapping(value = "/certificate_check")
	@ResponseBody
	public Msg checkCertificate(String rural_id) {
		boolean b = this.certificateService.countCertificateByRuralId(rural_id);
		if(b) {
			return Msg.success();
		}else {
			return Msg.fail();
		}
	}
	
	@RequestMapping(value = "/certificate_disease_check")
	@ResponseBody
	public Msg checkCertificate4disease(String rural_id,String disease_name) {
		
		boolean b = this.certificateService.countCertificateByDisease(disease_name, rural_id);
		
		if(b) {
			return Msg.success();
		}else {
			return Msg.fail();
		}
	}
	
	@RequestMapping(value = "/reimbursement_action")
	@ResponseBody
	public Msg doReimbursement(String member_name,String people_id,String rural_id,String disease_name,String year,
			                                            String family_adress,String status,String pay_money) {
		double money;
		
		double aleady_money = 0.0;
		//构造reimbursement_id
		SimpleDateFormat currentTime = new SimpleDateFormat("yyyyMMddHHmmss");
		
		String reimbursement_time = currentTime.format(new java.util.Date());
		
		String reimbursement_id = "R"+reimbursement_time;
		//判断报销时间是否在慢性病证的时间段内
		Certificate certificate = this.certificateService.findCertificateByDiseaseAndRuralId(disease_name,rural_id);
		
		int start_time = Integer.valueOf(certificate.getStart_time());
		
		int end_time = Integer.valueOf(certificate.getEnd_time());
		
		int CurrentYear = Integer.valueOf(year);
		
		double pay_money1 = Integer.valueOf(pay_money);
		
		if(start_time<=CurrentYear && CurrentYear<=end_time) {
			//1.查询当年报销政策(封顶线、报销比例)
			Policy policy = this.policyService.findPolicyByYear(year);
			//2.通过rural_id和年份查询该农民本年度的报销记录并统计已经报销的费用
			List<Reimbursement> reimbursementlist = this.reimbursementService.findReimbursementByRuralIdAndYear(rural_id,year);
			//3.计算本次报销费用：报销金额=（（封顶线-年度已报销金额）>=预报销金额）？预报销金额：（封顶线-年度已报销金额）
			if(reimbursementlist.isEmpty()) {
				 money = pay_money1*policy.getProportion();
			}else {
				for(int i=0;i<reimbursementlist.size();i++) {
					
				aleady_money+=reimbursementlist.get(i).getMoney();
					
				}
				 money = ((policy.getLine()-aleady_money)>=pay_money1*policy.getProportion())?
						          pay_money1*policy.getProportion():
						         (policy.getLine()-aleady_money);
				
			}
			System.out.println(aleady_money);
			System.out.println(money);
			Map<String,Object> map = new HashMap<String,Object>();
			
			map.put("reimbursement_id", reimbursement_id);
			
			map.put("member_name", member_name);
			
			map.put("people_id",people_id);
			
			map.put("rural_id", rural_id);
			
			map.put("disease_name",disease_name);
			
			map.put("family_adress", family_adress);
			
			map.put("year", year);
			
			map.put("money", money);
			
			map.put("status", status);
			
			this.reimbursementService.addReimbursement(map);
			
			return Msg.success().add("money", money).add("pay_money", pay_money).add("aleady_money", aleady_money);
			
		}else {
			
			return Msg.fail();
			
		}
	}
	
	@RequestMapping(value = "/reimbursement_list")
	public String reimbursementList(Model model, HttpServletRequest request, @RequestParam(defaultValue = "1") Integer pageNum,
			@RequestParam(defaultValue = "5") Integer pageSize, String keyword) throws Exception {

		Page<Reimbursement> page = this.reimbursementService.findReimbursementPagelist(keyword, pageSize, pageNum);
		System.out.println("!!!!!!!!!!!!!!!");
		model.addAttribute("page", page);

		return "/reimbursement/reimbursement_list";
	}
	
	@RequestMapping(value="/reimbursement_update")
	public String updateReimbursement(String reimbursement_id,Model model) {
		
		Reimbursement reimbursement = this.reimbursementService.findReimbursementById(reimbursement_id);
		
		model.addAttribute("reimbursement", reimbursement);
		
		return"/reimbursement/reimbursement_update";
	}
	
	@RequestMapping(value = "/reimbursement_update_action")
	@ResponseBody
	public Msg updateReimbursementAction(String reimbursement_id,String status) {
		
		try {
			
			Map<String,Object>map = new HashMap<String,Object>();
			
			map.put("reimbursement_id", reimbursement_id);
			
			map.put("status", status);
			
			this.reimbursementService.updateReimbursement(map);
			
			return Msg.success();
			
		}catch (Exception e) {
			
			e.printStackTrace();
			
			return Msg.fail();
		}
	}
}
